# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName : p29.py
# @Time     : 2024/5/12 19:32
# @Author   : Robot-Zsj
"""
description:

找城市

https://fcqian.blog.csdn.net/article/details/127711368

i:
3
3
1 2 3 0
1 3 1 0
2 3 5 0

o:
4

"""


class UnionFindSset:
    def __init__(self, n):
        self.fa = [i for i in range(n)]
        self.count = n

    def find(self, x):
        if x != self.fa[x]:
            self.fa[x] = self.find(self.fa[x])
            return self.fa[x]
        return x

    def union(self, x, y):
        x_fa = self.find(x)
        y_fa = self.find(y)

        if x_fa != y_fa:
            self.fa[y_fa] = x_fa
            self.count -= 1


n = int(input())
m = int(input())

edges = []

for _ in range(m):
    x, y, z, p = map(int, input().split())

    if p == 0:
        edges.append([x, y, z])
    else:
        edges.append([x, y, 0])


def kruskal():
    minWeight = 0

    edges.sort(key=lambda x: x[2])

    ufs = UnionFindSset(n + 1)

    for x, y, z in edges:
        if ufs.find(x) != ufs.find(y):
            minWeight += z
            ufs.union(x, y)

            if ufs.count == 2:
                return minWeight
    return -1


print(kruskal())